package com.boot.controller;

import com.boot.entity.Product;
import com.boot.entity.R;
import com.boot.exception.ServiceException;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    private String uploadPath = "D:\\www\\img\\";


    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public R upload(MultipartFile file){
        File pathFile = new File(uploadPath);

        if (!pathFile.exists()){
            pathFile.mkdir();
        }

        String filename = UUID.randomUUID().toString();

        try (
                InputStream is = file.getInputStream();
                OutputStream os = new FileOutputStream(new File(uploadPath,filename));
        ){
            IOUtils.copy(is,os);
        }catch (Exception e){
            return R.fail(401,"上传失败");
        }


        return R.success(new Product().setCover(filename));
    }


    /**
     * 文件下载
     * @param coverName
     * @param resp
     */
    @RequestMapping("/download")
    public void download(String coverName, HttpServletResponse resp){

        File file = new File(uploadPath,coverName);

        if (!file.exists()) {
            throw new ServiceException(401,"文件不存在");
        }

        try (
            InputStream is = new FileInputStream(file);
            OutputStream os = resp.getOutputStream();
        ){
            IOUtils.copy(is,os);
        }catch (Exception e){
            throw new ServiceException(402,"下载失败");
        }

    }
}
